from flask import Flask, request, jsonify
import ddddocr
import os
import dotenv

dotenv.load_dotenv()

app = Flask(__name__)
ocr = ddddocr.DdddOcr()

# 预定义的授权令牌
AUTH_TOKEN = os.getenv('AUTH_TOKEN')

def check_auth(token):
    """检查提供的 token 是否有效"""
    return token == AUTH_TOKEN


@app.route('/ocr', methods=['POST'])
def ocr_base64_image():
    auth_header = request.headers.get('Authorization')

    if not auth_header or not check_auth(auth_header):
        return jsonify({'code': 401, 'msg': 'Unauthorized', 'data': ''})

    data = request.json
    if 'image' not in data:
        return jsonify({'code': 400, 'msg': 'No image provided', 'data': ''})

    try:
        image_data = data['image']
        # 使用指定长度进行验证码识别
        result = ocr.classification(image_data)
        return jsonify({'code': 200, 'msg': 'Success', 'data': result})
    except Exception as e:
        return jsonify({'code': 500, 'msg': str(e), 'data': ''})


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=2003, debug=True)
